#include"linklist.h"

linklist init_list(void)  //初始化链表
{
    linklist head = malloc(sizeof(linknode));
    if(head != NULL)
        head->next = NULL;
    return head;
}

linklist new_node(int data)  //新增节点
{
    linklist new = malloc(sizeof(linknode));
    if(new != NULL){
        new->data = data;
        new->next = NULL;
    }
    return new;
}

linklist find_tail(linklist head) //找到尾节点
{
    if(head == NULL)
        return NULL;
    linklist tail;
    for(tail = head; tail->next != NULL; tail = tail->next);
    return tail;
}

void list_add_tail(linklist head, linklist new)  //尾插法插入新节点
{
    if(head == NULL || new == NULL)
        return;
    linklist tail = find_tail(head);
    tail->next = new;
}

linklist del_node(linklist head, int data)  //剔除指定节点
{
    linklist p, k;
    for(p = head; p->next != NULL && p->next->data != data; p = p->next);
    if(p->next == NULL)
        return NULL;
    k = p->next;
    p->next = p->next->next;
    k->next = NULL;
    return k;
}

void reverse_list(linklist head)  //反转链表
{
    if(head->next == NULL || head->next->next == NULL)
        return;
    linklist phead = head->next;
    head->next = NULL;
    while(phead != NULL){
        linklist tail = find_tail(head);
        linklist ptail = phead;
        linklist prvtail = NULL;
        while(ptail->next != NULL){
            prvtail = ptail;
            ptail = ptail->next;
        }
        if(prvtail == NULL)
            phead = NULL;
        else
            prvtail->next = NULL;
        tail->next = ptail;
    }
}

void new_reverse_list(linklist head)
{
    if(head == NULL || head->next == NULL)
        return;
    linklist p = NULL;
    linklist k = NULL;
    for(p = head->next, head->next = NULL; p != NULL; p = k){
        k = p->next;
        p->next = head->next;
        head->next = p;
    }
}

void my_reverse_list(linklist head)
{
    if(head == NULL || head->next == NULL)
        return;
    linklist p = head->next;
    linklist k = NULL;
    for(head->next = NULL;p != NULL; p = k){
        k = p->next;
        p->next = head->next;
        head->next = p;
    }
}

void list_for_each(linklist head)  //遍历输出链表
{
    for(linklist p = head->next; p != NULL; p = p->next)
        printf("%d\t", p->data);
    printf("\n");
}

void destory_list(linklist head)  //销毁链表
{
    for(linklist p = head; p->next != NULL;){
        linklist k = p->next;
        p->next = k->next;
        free(k);
    }
}